﻿<?php
/**
 * DESCRIPTION:
 *  abstract class for all Models
 * FIELDS:
 *  public $id is an id of object in db
 *  private $table is a name of db table storing the objects
 *  public $fields is the object data from db
 *  private $associated stores the table associations (like FK's)
 * METHODS:
 *  public void __construct($id=null, $table=__CLASS__) class constructor
 *  public array gettags() gets all tags for object instance
 * ======
 * @author at8eqeq3
 */
abstract class model {
    public $id;
    private $table;
    public $fields = array();
    //private $associated = array();
    
    public function __construct($id = null, $table = __CLASS__){
        //first, get a correct db table name
        $this->table = $table."s"; //better way is to write a pluralisation method in strconv (as in ROR)

        //if $id is present, find it in db, else just create an empty object
        if($id){
            $this->id = $id;
            $query = "select * from $this->table where id=\"$this->id\"";
            $result = mysql_query($query);
            if(mysql_num_rows($result)){
                $this->fields = mysql_fetch_assoc($result);
            }else{
                $e = new error(__FILE__, __LINE__, "Объект с идентификатором $this->id не найден в таблице $this->table");
                $e->raise();
            }
        }
    }

    /*private function associate($a){ //not implemented yet(((
        $query = "select id from $a where $this->table=\"$this->id\"";
        echo $query;
        $result = mysql_query($query);
        if(mysql_num_rows($result)){
            while($row = mysql_fetch_assoc($result)){
                print_r($row);
                array_push($this->associated[$a], $row);
            }
        }
    }*/

    public function gettags(){
        $tags = array();
        $query = "select tagvalue from tags where tagownermodel=\"$this->table\" and tagowner=\"$this->id\"";
        $result = mysql_query($query);
        if(mysql_num_rows($result)){
            while($row = mysql_fetch_row($result)){
                array_push($tags, $row[0]);
            }
        }
        return $tags;
    }
}
?>
